package com.sansi.bleFloodlight.ble;

import android.app.Activity;
import android.os.Handler;

import com.a1anwang.okble.client.core.OKBLEDevice;
import com.a1anwang.okble.client.core.OKBLEDeviceImp;
import com.a1anwang.okble.client.core.OKBLEDeviceListener;
import com.a1anwang.okble.client.core.OKBLEOperation;
import com.a1anwang.okble.client.scan.BLEScanResult;

import com.my.httpapi.api.baseUtils.LogUtils;
import com.my.httpapi.api.baseUtils.Toast;
import com.sansi.bleFloodlight.ble.bleInterface.BleManageListener;
import com.sansi.bleFloodlight.ble.bleInterface.IBleManage;
import com.sansi.bleFloodlight.utils.Constant;

import java.util.ArrayList;
import java.util.List;

public class BleManageUtils implements IBleManage {
    private BleManageListener bleManageListener;
    private OKBLEDevice okbleDevice;//当前的设备
    private Activity activity;

    public static final int SUCESS = 0;
    public static final int FAIL = 1;
    private int localStatus = -1;//当前状态是成功还是失败的
    private static final int postDelayTime = 1000;

    private List<OKBLEDevice> list_device = new ArrayList<>();

    public BleManageUtils(Activity activity, BleManageListener bleManageListener) {
        this.bleManageListener = bleManageListener;
        this.activity = activity;
    }

    @Override
    public boolean connect(boolean autoReconnect) {
        return okbleDevice.connect(autoReconnect);
    }

    @Override
    public void disConnectAll() {
        for (int i = 0; i < list_device.size(); i++) {
            list_device.get(i).disConnect(false);
        }
    }

    @Override
    public void setBLEScanResult(BLEScanResult searchResult) {
        okbleDevice = new OKBLEDeviceImp(activity, searchResult);
        okbleDevice.addDeviceListener(okbleDeviceListener);
        list_device.add(okbleDevice);
    }

    @Override
    public void writeData(byte[] data) {
        okbleDevice.addWriteOperation(Constant.WRITE_UUID, data, new OKBLEOperation.WriteOperationListener() {
            @Override
            public void onWriteValue(final byte[] byteValue) {
            }

            @Override
            public void onFail(int code, final String errMsg) {
            }

            @Override
            public void onExecuteSuccess(OKBLEOperation.OperationType type) {

            }
        });
    }

    private OKBLEDeviceListener okbleDeviceListener = new OKBLEDeviceListener() {
        @Override
        public void onConnected(String deviceTAG) {
            LogUtils.e("onConnected：" + deviceTAG);
            activity.runOnUiThread(() -> new Handler().postDelayed(() -> notifyOrIndicate(), postDelayTime));
        }

        @Override
        public void onDisconnected(String deviceTAG) {
            LogUtils.e("onDisconnected：" + deviceTAG);
            activity.runOnUiThread(() -> disconnected());
        }

        @Override
        public void onReadBattery(String deviceTAG, int battery) {
            LogUtils.e("onReadBattery：" + deviceTAG);
        }

        @Override
        public void onReceivedValue(String deviceTAG, final String uuid, byte[] value) {
            String advertisingStr = ScanRecordUtil.bytesToHex(value);
            LogUtils.e("onReceivedValue：" + deviceTAG + ":" + advertisingStr);
            final String code = advertisingStr.substring(6, 8);
            if ("00".equals(code)) {
                localStatus = 0;
            } else {
                localStatus = 1;
            }
            LogUtils.e("code：" + code);
            activity.runOnUiThread(() -> receivedValue(uuid, advertisingStr));
        }

        @Override
        public void onWriteValue(String deviceTAG, String uuid, byte[] value, boolean success) {
            String advertisingStr = ScanRecordUtil.bytesToHex(value);
            LogUtils.e("onWriteValue：" + deviceTAG + ":" + advertisingStr);
        }

        @Override
        public void onReadValue(String deviceTAG, String uuid, byte[] value, boolean success) {
            String advertisingStr = ScanRecordUtil.bytesToHex(value);
            LogUtils.e("onReadValue：" + deviceTAG + ":" + advertisingStr);
        }

        @Override
        public void onNotifyOrIndicateComplete(String deviceTAG, String uuid, boolean enable, boolean success) {
            LogUtils.e("onNotifyOrIndicateComplete：" + deviceTAG + "    success:" + success);
        }
    };

    private void notifyOrIndicate() {
        okbleDevice.addNotifyOrIndicateOperation(Constant.WRITE_UUID, true, new OKBLEOperation.NotifyOrIndicateOperationListener() {
            @Override
            public void onNotifyOrIndicateComplete() {
                LogUtils.e("onNotifyOrIndicateComplete");
                activity.runOnUiThread(() -> new Handler().postDelayed(() -> openNotify(), postDelayTime));
            }

            @Override
            public void onFail(int code, final String errMsg) {
                LogUtils.e("onFail");
                activity.runOnUiThread(() -> new Handler().postDelayed(() -> openNotify(), postDelayTime));
            }

            @Override
            public void onExecuteSuccess(OKBLEOperation.OperationType type) {
                LogUtils.e("onExecuteSuccess");
            }
        });
    }

    private void openNotify() {
        if (bleManageListener != null) bleManageListener.openNotify();
    }

    private void disconnected() {
        Toast.show("连接已断开");
        if (bleManageListener != null) bleManageListener.onDisconnected();
    }

    private void receivedValue(String uuid, String value) {
        if (bleManageListener != null) bleManageListener.onReceivedValue(uuid, localStatus, value);
    }
}
